import { Menu } from 'antd'
import { useLocation, useNavigate } from 'react-router-dom'
import {
  IconAccounts,
  IconFinance,
  IconHome,
  IconPurchase,
  IconSales,
  IconSetting,
  IconWarehouse
} from '@/components/icon/index.jsx'
import Logo from '@/layouts/components/menu/Logo/index.jsx'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { addTab } from '@/store/slices/tabsSlice'

const LayoutMenu = (props) => {
  const items = [
    {
      label: '首页',
      key: '/dashboard',
      icon: <IconHome />
    },
    {
      label: '基础资料',
      key: '/basicData',
      icon: <IconSetting />,
      children: [
        {
          label: '部门管理',
          key: '/department'
        },
        {
          label: '产品管理',
          key: '/product'
        },
        {
          label: '供应商管理',
          key: '/supplier'
        }
      ]
    },
    {
      label: '销售管理',
      key: '/salesManage',
      icon: <IconSales />
    },
    {
      label: '采购管理',
      key: '/purchaseManage',
      icon: <IconPurchase />
    },
    {
      label: '库存管理',
      key: '/warehouseManage',
      icon: <IconWarehouse />
    },
    {
      label: '财务管理',
      key: '/financeManage',
      icon: <IconAccounts />
    },
    {
      label: '账务管理',
      key: '/accountsManage',
      icon: <IconFinance />
    }
  ]

  // 默认
  const [pathKey, setPathKey] = useState()

  const { pathname } = useLocation()

  const [openKeys, setOpenKeys] = useState([])

  // 当path改变是，执行的函数
  useEffect(() => {
    setPathKey(pathname)
    navigate(pathname)
  }, [pathKey, pathname])

  const navigate = useNavigate()
  const dispatch = useDispatch()

  /**
   * 菜单点击事件
   * @param route
   */
  const onMenuClick = ({ key }) => {
    const menuItem =
      items.find((item) => item.key === key) ||
      items.flatMap((item) => item.children || [])
        .find((item) => item.key === key)

    if (menuItem) {
      dispatch(addTab({
          key: key,
          label: menuItem.label
        })
      )
    }
    navigate(key)
  }

  // 设置当前展开的 subMenu
  const onOpenChange = (openKeys) => {
    if (openKeys.length === 0 || openKeys.length === 1) {
      return setOpenKeys(openKeys)
    }
    const latestOpenKey = openKeys[openKeys.length - 1]
    if (latestOpenKey.includes(openKeys[0])) {
      return setOpenKeys(openKeys)
    }
    setOpenKeys([latestOpenKey])
  }

  return (
    <div className='layout-menu'>
      <Logo />
      <Menu
        mode='inline'
        selectedKeys={[pathKey]}
        items={items}
        onClick={onMenuClick}
        theme={props.theme}
        openKeys={openKeys}
        onOpenChange={onOpenChange}
      />
    </div>
  )
}

export default LayoutMenu
